package com.dashan.backend.datastore;

import java.util.Set;
import static com.dashan.Constants.SEPERATOR;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dashan.backend.AccessControlManager;
import com.dashan.backend.XmlSerializable;
import com.dashan.backend.AccessControlManager.Permission;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class DsFriendGroup implements XmlSerializable {
    @PrimaryKey
    @Persistent
    private Key key;

    @Persistent
    private String groupName;
    
    @Persistent
    private Long permissionBits;
    
    private Set<Permission> permissions;

    public DsFriendGroup(String userName, String groupName, Long permissionBits) {
        this.key = buildKey(userName, groupName);
        this.groupName = groupName;
        this.permissionBits = permissionBits;
        this.permissions = AccessControlManager.PermissionBits2Set(permissionBits);
    }
    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String userName, String groupName) {
        this.groupName = groupName;
        this.key = buildKey(userName, groupName);
    }

    public long getPermissionBits() {
        return permissionBits;
    }

    public void setPermissionBits(long permissionBits) {
        this.permissionBits = permissionBits;
        permissions = null;
        permissions = AccessControlManager.PermissionBits2Set(permissionBits);
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }
    
    public Key getKey() {
        return key;
    }
    
    public Element getXmlElement(Document xmlDoc) {
        Element root = xmlDoc.createElement("friendGroup");
        
        Element ele = null;
        ele = xmlDoc.createElement("groupName");
        ele.appendChild(xmlDoc.createTextNode(getGroupName()));
        root.appendChild(ele);
        ele = xmlDoc.createElement("permission");
        String permission = "";
        for (Permission p : getPermissions()) {
            permission += p.getName() + SEPERATOR;
        }
        ele.appendChild(xmlDoc.createTextNode(permission));
        root.appendChild(ele);
        return root;
    }
    
    public static Key buildKey(String userName, String groupName) {
        KeyFactory.Builder builder = new KeyFactory.Builder(DsUser.class.getSimpleName(), userName);
        builder.addChild(DsFriendGroup.class.getSimpleName(), groupName);
        return builder.getKey();
    }
}
